import React, {useState} from "react";
import {Button, Cascader, Form, Input, Modal} from "antd";
import {observer} from "mobx-react";
import categoryStore from "../../../category/store/CategoryStore";
import quickTestStore from "../store/QuickTestStore";
import tabQuickTestStore from "../../store/TabQuickTestStore";

/**
 * 保存为接口组件
 * 用于将当前测试用例保存为API接口
 */
const SaveToApi = (props) => {
    const { findCategoryTree } = categoryStore;
    const { 
        baseInfo,
        headerList,
        queryList,
        requestBodyType,
        formList,
        formUrlList,
        rawInfo,
        preScript,
        afterScript 
    } = tabQuickTestStore;
    const { saveToApi } = quickTestStore;

    const [isModalOpen, setIsModalOpen] = useState(false);
    const [form] = Form.useForm();
    const workspaceId = localStorage.getItem('workspaceId');
    const [cascaderCategoryId, setCascaderCategoryId] = useState();
    const [categoryList, setCategoryList] = useState([]);

    /**
     * 显示保存接口弹窗
     * 获取分类树数据并设置表单初始值
     */
    const showModal = async () => {
        const categoryList = await findCategoryTree({workspaceId});
        setCategoryList(categoryList);
        setIsModalOpen(true);
        form.setFieldsValue({
            path: handleApiPath(baseInfo.path),
        });
    };

    /**
     * 处理API路径
     * 从完整URL中提取路径部分
     * @param {string} inputUrl - 输入的URL
     * @returns {string} 处理后的API路径
     */
    const handleApiPath = (inputUrl) => {
        try {
            const url = new URL(inputUrl);
            const path = url.pathname + url.search + url.hash;
            return (path && path !== "/") ? path : inputUrl;
        } catch (e) {
            return inputUrl;
        }
    };

    /**
     * 处理表单提交
     * 收集表单数据并调用保存接口方法
     */
    const handleOk = async () => {
        // 等待表单验证完成
        const values = await form.validateFields();
        const path = handleApiPath(baseInfo.path);
        
        // 构建保存接口所需的数据结构
        const saveToApiData = {
            httpApi: {
                apix: {
                    path,
                    name: values.name,
                    categoryId: cascaderCategoryId,
                },
                node: {
                    name: values.name,
                    workspace: {id: workspaceId},
                    parentId: cascaderCategoryId,
                    methodType: baseInfo.methodType,
                }
            },
            headerList: headerList.slice(0, -1),
            queryList: queryList.slice(0, -1),
            request: {
                bodyType: requestBodyType,
                preScript: preScript.scriptex,
                afterScript: afterScript.scriptex
            },
            formList: formList.slice(0, -1),
            formUrlList: formUrlList.slice(0, -1),
            raw: rawInfo
        };

        await saveToApi(saveToApiData);
        setIsModalOpen(false);
    };

    /**
     * 关闭弹窗
     */
    const handleCancel = () => {
        setIsModalOpen(false);
    };

    /**
     * 处理分类选择变化
     * @param {Array} value - 级联选择器的值
     */
    const changeCategory = (value) => {
        const list = value.slice(-1);
        setCascaderCategoryId(list[0]);
    };

    return (
        <>
            <span
                className={"link-text"}
                style={{
                    display: 'inline-block',
                    padding: '6px 16px',
                    backgroundColor: '#f5f5f5',
                    borderRadius: '4px',
                    cursor: 'pointer',
                    transition: 'all 0.3s',
                    fontSize: '14px',
                    lineHeight: "26px",
                    height: "38px",
                    whiteSpace: 'nowrap',
                    width: 'fit-content',
                    ':hover': {
                        backgroundColor: '#40a9ff',
                        borderColor: '#40a9ff'
                    }
                }}
                onClick={showModal}
            >
                保存为接口
            </span>
            <Modal
                destroyOnClose={true}
                title='保存为接口'
                open={isModalOpen}
                onCancel={handleCancel}
                onOk={handleOk}
                okText="提交"
                cancelText="取消"
            >
                <Form
                    preserve={false}
                    className='testCase-edit-form'
                    form={form}
                    layout="vertical"
                >
                    <Form.Item
                        label="名称"
                        name="name"
                        rules={[{
                            required: true,
                            message: '请输入接口名称!'
                        }]}
                    >
                        <Input placeholder="请输入名称"/>
                    </Form.Item>
                    <Form.Item
                        label="路径"
                        name="path"
                        rules={[{
                            required: true,
                            message: '请输入接口路径!'
                        }]}
                    >
                        <Input disabled={true} />
                    </Form.Item>
                    <Form.Item
                        label="分组"
                        name="category"
                        rules={[{ required: true, message: '请选择接口分组!' }]}
                    >
                        <Cascader
                            fieldNames={{ label: 'name', value: 'id', children: 'children' }}
                            options={categoryList}
                            onChange={changeCategory}
                            changeOnSelect
                            expandTrigger="hover"
                        />
                    </Form.Item>
                </Form>
            </Modal>
        </>
    );
};

export default observer(SaveToApi);